package com.example.lawyer.netty.handler;

import com.example.lawyer.netty.NettyConfig;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/***
 * TCP长链接解码
 */
public class TcpMessageDecoder extends ByteToMessageDecoder {

    @Override
    public Object decode(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {


        int i1 = byteBuf.readerIndex();
        System.out.println("指针位置"+i1);


        int len = byteBuf.readableBytes();
        System.out.println("收到消息长度"+len);
        if(len<=0)
        {

            return null;
        }
        int coni = len - 8;
        if(len<=8)
        {
            System.out.println("消息长度不合理");
            byteBuf.skipBytes(len);
            return null;
        }
        byteBuf.markReaderIndex();

        int i = byteBuf.readInt();
        System.out.println(i);
        if(i!= NettyConfig.NETTY_TOP_KEY)
        {
            System.out.println("消息头部不一致");
            byteBuf.skipBytes(len-4);
            return null;
        }
        int l = byteBuf.readInt();
        System.out.println("定长"+l);
        if(len<l)
        {
            System.out.println("消息未完全收到");
            byteBuf.resetReaderIndex();
            return null;
        }
        if(l>10240)
        {
            System.out.println("消息过大");
            byteBuf.skipBytes(l);
            return null;
        }
        int ri = byteBuf.readerIndex();
        int wi = byteBuf.writerIndex();
        System.out.println("读"+ri);
        System.out.println("写"+wi);
        if(ri>wi)
        {
            System.out.println("消息长度有误");
            byteBuf.resetReaderIndex();
            return null;
        }
        byte[] bytes = new byte[coni];
        byteBuf.readBytes(bytes);
        String string = new String(bytes);
        System.out.println("收到消息"+string);
        return string;
    }
}
